import React, { memo, useEffect, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import NavBar from '../../components/Navbar'
import './index.less'
import { addBankData, editBankInfo } from '../../api/union'
import { Toast } from 'antd-mobile'
import { sendCode, checkCode } from '../../api/mine'

const VerifyCode = memo(({ onClick, seconds = 30 }) => {
  const [time, setTime] = useState(0)
  const timer = useRef(null)

  useEffect(() => {
    timer.current && clearInterval(timer.current)
    return () => timer.current && clearInterval(timer.current)
  }, [])

  useEffect(() => {
    if (time === seconds) timer.current = setInterval(() => setTime((time) => --time), 1000)
    else if (time <= 0) timer.current && clearInterval(timer.current)
  }, [time])

  const getCode = () => {
    if (time) return
    // 作为组件使用
    onClick?.(() => {
      setTime(seconds)
    })
  }

  return (
    <div onClick={getCode} className="get_code">
      {time ? `${time}秒后获取` : '获取验证码'}
    </div>
  )
})

function AddBank() {
  const params = useSearchParams()[0]

  const [data, setData] = useState({})
  const [hasCode, setHasCode] = useState(false)
  const navigate = useNavigate()

  const addData = () => {
    if (!hasCode) {
      Toast.show({
        content: '请获取验证码'
      })
      return false
    }
    if (data.phone?.length < 11) {
      Toast.show({
        content: '请检查手机号是否正确'
      })
      return false
    }
    Toast.show({ content: '提交中', icon: 'loading', maskClickable: false })
    checkCode({
      phone: data.phone,
      code: data.code
    })
      .then((res) => {
        ;(params.get('edit_type') === 'bank'
          ? editBankInfo({
              ...data,
              bank_id: data.id
            })
          : addBankData(data)
        )
          .then((res) => {
            console.log(res)
            Toast.clear()
            Toast.show({
              content: '添加成功',
              icon: 'success'
            })
            setTimeout(() => {
              // history.goBack()
              navigate(-1)
            }, 1500)
          })
          .catch((err) => {
            Toast.show({
              content: err.message || '系统错误'
            })
          })
      })
      .catch((err) => {
        Toast.show({
          content: err.message || '验证码错误'
        })
      })
  }

  const getCode = (call) => {
    if (!data?.phone || data.phone?.length < 11) {
      Toast.show({
        content: '请检查手机号是否正确'
      })
    } else {
      sendCode({ phone: data.phone })
        .then((res) => {
          call?.()
          setHasCode(true)
        })
        .catch((err) => {
          Toast.show({
            content: err.message
          })
        })
    }
  }

  useEffect(() => {
    if (params.get('edit_type') === 'bank' && localStorage.getItem('bank_info')) {
      setData(JSON.parse(localStorage.getItem('bank_info')))
    }
  }, [])

  return (
    <div className="add_bank_wrap">
      <NavBar title="添加银行卡" />
      <div className="add_bank_form">
        <input
          name="bank_no"
          className="input"
          type="text"
          placeholder="银行卡号"
          value={data?.bank_no}
          onChange={(e) => setData({ ...data, bank_no: e.target.value })}
          maxLength={22}
        />
        <input
          name="bank_name"
          className="input"
          type="text"
          placeholder="开户银行"
          value={data?.bank_name}
          onChange={(e) => setData({ ...data, bank_name: e.target.value })}
          maxLength={12}
        />
        <input
          name="phone"
          className="input"
          type="text"
          placeholder="银行预留电话号"
          value={data?.phone}
          onChange={(e) => setData({ ...data, phone: e.target.value })}
          maxLength={13}
        />
        <div className="phone_content">
          <input
            name="code"
            className="input"
            type="text"
            placeholder="验证码"
            onChange={(e) => setData({ ...data, code: e.target.value })}
            maxLength={8}
          />
          <VerifyCode onClick={getCode} />
        </div>

        <div onClick={addData} className={`submit_btn active`}>
          确定
        </div>
      </div>
    </div>
  )
}

export default AddBank

// export VerifyCode;
